package com.example.shutdown_v1.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * 定时任务配置
 * 配置线程池以支持并发执行多个定时任务
 */
@Slf4j
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {
    
    /**
     * 配置定时任务线程池
     * 支持多个定时任务并发执行
     */
    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        
        // 线程池大小：支持多个定时任务并发执行
        scheduler.setPoolSize(5);
        
        // 线程名称前缀
        scheduler.setThreadNamePrefix("scheduled-task-");
        
        // 等待所有任务完成后再关闭线程池
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        
        // 等待时间（秒）
        scheduler.setAwaitTerminationSeconds(60);
        
        // 拒绝策略：调用者执行
        scheduler.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
        
        // 初始化
        scheduler.initialize();
        
        log.info("定时任务线程池初始化完成 - 线程池大小: {}", scheduler.getPoolSize());
        
        return scheduler;
    }
    
    /**
     * 配置定时任务注册器
     */
    @Override
    public void configureTasks(@org.springframework.lang.NonNull ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskScheduler());
    }
}

